<template>
  <div class="p-6 space-y-4">
    <el-card shadow="never" class="rounded-lg">
      <el-form :model="filters" label-position="top" class="search-form" @keyup.enter.native="handleQuery">
        <el-row :gutter="12" align="bottom">
          <el-col :xs="24" :sm="12" :lg="5">
            <el-form-item label="设备名称">
              <el-input v-model="filters.sbmc" placeholder="请输入" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="5">
            <el-form-item label="设备位号">
              <el-input v-model="filters.sbwh" placeholder="请输入" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="5">
            <el-form-item label="设备类型">
              <el-select v-model="filters.sblx" clearable placeholder="请选择">
                <el-option v-for="item in equipmentTypeOptions" :key="item" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="5">
            <el-form-item label="设备等级">
              <el-select v-model="filters.sbdj" clearable placeholder="请选择">
                <el-option v-for="item in equipmentGradeOptions" :key="item" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="5">
            <el-form-item label="所属部门">
              <el-cascader
                v-model="filters.createDept"
                :options="departmentTreeOptions"
                :props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'bmmc' }"
                :show-all-levels="false"
                clearable
                :remote-method="getDepartmentTree"
                placeholder="请选择"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="4" class="flex justify-end items-end gap-2">
            <el-button type="primary" :loading="queryLoading" @click="handleQuery">
              <el-icon class="mr-1">
                <Search />
              </el-icon>
              查询
            </el-button>
            <el-button :icon="Plus" @click="onCreate()">新增</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card shadow="never" class="rounded-lg">
      <div v-loading="tableLoading">
        <el-table :data="tableData" border>
          <el-table-column label="序号" type="index" width="80" align="center" :index="indexMethod" />
          <el-table-column label="设备位号" prop="sbwh" min-width="120" />
          <el-table-column label="设备名称" prop="sbmc" min-width="160" />
          <el-table-column label="设备类型" prop="sblx" min-width="140">
            <template #default="scope">
              <el-tag :type="equipmentTypeTagType(scope.row.sblx)">{{ equipmentTypeKeyName[scope.row.sblx] || '-' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="是否特种设备" min-width="140" align="center">
            <template #default="scope">
              <el-tag :type="specialEquipmentTagType(scope.row.tzsbNy)">{{ specialEquipmentKeyName[scope.row.tzsbNy] || '-' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="是否为安全附件" min-width="140" align="center">
            <template #default="scope">
              <el-tag :type="safetyAttachmentTagType(scope.row.aqfjNy)">{{ safetyAttachmentKeyName[scope.row.aqfjNy] || '-' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="设备等级" prop="sbdj" min-width="120">
            <template #default="scope">
              <el-tag :type="equipmentGradeTagType(scope.row.sbdj)">{{ equipmentGradeKeyName[scope.row.sbdj] || '-' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="所属部门" prop="createDeptName" min-width="140" />
          <el-table-column label="状态" width="120" align="center">
            <template #default="scope">
              <el-tag :type="equipmentStatusTagType(scope.row.sbzt)">{{ equipmentStatusKeyName[scope.row.sbzt] || '-' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="安装位置" min-width="160">
            <template #default="scope">
              <el-tooltip placement="top" :content="scope.row.azwz">
                <span class="truncate block max-w-48"> {{ scope.row.azwz }} </span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160" align="center">
            <template #default="scope">
              <div class="flex justify-center items-center gap-2">
                <el-button link type="primary" :icon="Edit" @click="onView(scope.row)">详情</el-button>
                <el-button link type="danger" @click="onDelete(scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
          <template #empty>
            <el-empty description="暂无数据" />
          </template>
        </el-table>
      </div>

      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog v-model="detailVisible" :title="detailTitle" width="860px" destroy-on-close>
      <template #header>
        <div class="flex items-center justify-between pr-10">
          <div class="flex items-center gap-2">
            <div class="w-1 h-6 bg-#5B8FF9" />
            <div class="text-lg font-600">
              <template v-if="formOperationType === FormOperationTypeEnum.ADD"> 新增基础设备 </template>
              <template v-else>
                {{ detailTitle }}
              </template>
            </div>
          </div>
          <div>
            <el-button v-if="formOperationType !== FormOperationTypeEnum.ADD" type="primary" @click="onEdit">
              <svg-icon icon-class="edit-1"></svg-icon>
              编辑
            </el-button>
          </div>
        </div>
      </template>
      <el-form ref="formRef" :model="detailRecord" :rules="formRules" label-position="left" label-width="110px" class="w-full">
        <el-row :gutter="16" class="px-5">
          <el-col :xs="24" :md="12">
            <el-form-item label="设备位号" prop="sbwh"
              ><span v-if="viewForm">{{ detailRecord?.sbwh || '-' }}</span
              ><el-input v-else v-model="detailRecord.sbwh" placeholder="请输入" clearable
            /></el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="设备名称" prop="sbmc"
              ><span v-if="viewForm">{{ detailRecord?.sbmc || '-' }}</span
              ><el-input v-else v-model="detailRecord.sbmc" placeholder="请输入" clearable
            /></el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="所属部门" prop="createDept"
              ><span v-if="viewForm">{{ detailRecord?.createDeptName || '-' }}</span>
              <el-cascader
                v-else
                v-model="detailRecord.createDept"
                :options="departmentTreeOptions"
                :props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'bmmc' }"
                :show-all-levels="false"
                clearable
                style="width: 100%"
                placeholder="请选择"
            /></el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="所属装置" prop="sszz"
              ><span v-if="viewForm">{{ detailRecord?.sszzmc || '-' }}</span>
              <el-select v-else v-model="detailRecord.sszz" placeholder="请选择" clearable>
                <el-option v-for="(item, index) in belongDeviceOptions" :key="index" :label="item.sczzmc" :value="item.id" /> </el-select
            ></el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="设备主次" prop="sbzc"
              ><span v-if="viewForm"
                ><el-tag :type="equipmentPriorityTagType(detailRecord.sbzc)">{{ equipmentPriorityKeyName[detailRecord.sbzc] || '-' }}</el-tag></span
              >
              <el-select v-else v-model="detailRecord.sbzc" placeholder="请选择" clearable>
                <el-option v-for="(item, index) in equipmentPriorityOptions" :key="index" :label="item.label" :value="item.value" /> </el-select
            ></el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="设备类型" prop="sblx"
              ><span v-if="viewForm"
                ><el-tag :type="equipmentTypeTagType(detailRecord.sblx)">{{ equipmentTypeKeyName[detailRecord.sblx] || '-' }}</el-tag></span
              ><el-select v-else v-model="detailRecord.sblx" placeholder="请选择" clearable>
                <el-option v-for="(item, index) in equipmentTypeOptions" :key="index" :label="item.label" :value="item.value" /> </el-select
            ></el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="是否特种设备" prop="tzsbNy"
              ><span v-if="viewForm"
                ><el-tag :type="specialEquipmentTagType(detailRecord.tzsbNy)">{{ specialEquipmentKeyName[detailRecord.tzsbNy] || '-' }}</el-tag></span
              ><el-select v-else v-model="detailRecord.tzsbNy" placeholder="请选择" clearable>
                <el-option v-for="(item, index) in specialEquipmentOptions" :key="index" :label="item.label" :value="item.value" /> </el-select
            ></el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="特种设备分类" prop="tzsbfl"
              ><span v-if="viewForm"
                ><el-tag :type="specialEquipmentTypeTagType(detailRecord.tzsbfl)">{{
                  specialEquipmentTypeKeyName[detailRecord.tzsbfl] || '-'
                }}</el-tag></span
              ><el-select v-else v-model="detailRecord.tzsbfl" placeholder="请选择" clearable>
                <el-option v-for="(item, index) in specialEquipmentTypeOptions" :key="index" :label="item.label" :value="item.value" /> </el-select
            ></el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="是否安全附件" prop="aqfjNy"
              ><span v-if="viewForm"
                ><el-tag :type="safetyAttachmentTagType(detailRecord.aqfjNy)">{{ safetyAttachmentKeyName[detailRecord.aqfjNy] || '-' }}</el-tag></span
              ><el-select v-else v-model="detailRecord.aqfjNy" placeholder="请选择" clearable>
                <el-option v-for="(item, index) in safetyAttachmentOptions" :key="index" :label="item.label" :value="item.value" /> </el-select
            ></el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="安全附件分类" prop="aqfjfl"
              ><span v-if="viewForm"
                ><el-tag :type="safetyAttachmentTypeTagType(detailRecord.aqfjfl)">{{
                  safetyAttachmentTypeKeyName[detailRecord.aqfjfl] || '-'
                }}</el-tag></span
              ><el-select v-else v-model="detailRecord.aqfjfl" placeholder="请选择" clearable>
                <el-option v-for="(item, index) in safetyAttachmentTypeOptions" :key="index" :label="item.label" :value="item.value" /> </el-select
            ></el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="设备等级" prop="sbdj"
              ><span v-if="viewForm"
                ><el-tag :type="equipmentGradeTagType(detailRecord.sbdj)">{{ equipmentGradeKeyName[detailRecord.sbdj] || '-' }}</el-tag></span
              ><el-select v-else v-model="detailRecord.sbdj" placeholder="请选择" clearable>
                <el-option v-for="(item, index) in equipmentGradeOptions" :key="index" :label="item.label" :value="item.value" /> </el-select
            ></el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="设备状态" prop="sbzt"
              ><span v-if="viewForm"
                ><el-tag :type="equipmentStatusTagType(detailRecord.sbzt)">{{ equipmentStatusMap[detailRecord.sbzt] || '-' }}</el-tag></span
              ><el-select v-else v-model="detailRecord.sbzt" placeholder="请选择" clearable>
                <el-option v-for="(item, index) in equipmentStatusOptions" :key="index" :label="item.label" :value="item.value" /> </el-select
            ></el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="规格型号" prop="sbxh"
              ><span v-if="viewForm">{{ detailRecord?.sbxh || '-' }}</span
              ><el-input v-else v-model="detailRecord.sbxh" placeholder="请输入" clearable
            /></el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="生产日期" prop="scrq"
              ><span v-if="viewForm">{{ detailRecord?.scrq || '-' }}</span
              ><el-date-picker
                v-else
                clearable
                v-model="detailRecord.scrq"
                style="width: 100%"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择"
            /></el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="使用年限" prop="synx"
              ><span v-if="viewForm">{{ detailRecord?.synx ?? '-' }}</span
              ><el-input v-else v-model="detailRecord.synx" placeholder="请输入" clearable
            /></el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="安装位置" prop="azwz"
              ><span v-if="viewForm">{{ detailRecord?.azwz || '-' }}</span
              ><el-input v-else v-model="detailRecord.azwz" placeholder="请输入" clearable
            /></el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="安装日期" prop="azrq"
              ><span v-if="viewForm">{{ detailRecord?.azrq || '-' }}</span
              ><el-date-picker
                v-else
                clearable
                v-model="detailRecord.azrq"
                style="width: 100%"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择"
            /></el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="启用日期" prop="qyrq"
              ><span v-if="viewForm">{{ detailRecord?.qyrq || '-' }}</span
              ><el-date-picker
                v-else
                clearable
                v-model="detailRecord.qyrq"
                style="width: 100%"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择"
            /></el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="维修保养周期" prop="whbyzq"
              ><span v-if="viewForm">{{ detailRecord?.whbyzq || '-' }}</span
              ><el-input v-else v-model="detailRecord.whbyzq" placeholder="请输入" clearable
            /></el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="维护保养单位" prop="whbydw"
              ><span v-if="viewForm"
                ><el-tag :type="maintenanceUpkeepUnitTagType(detailRecord.whbydw)">{{
                  maintenanceUpkeepUnitMap[detailRecord.whbydw] || '-'
                }}</el-tag></span
              ><el-select v-else v-model="detailRecord.whbydw" placeholder="请选择" clearable>
                <el-option v-for="(item, index) in maintenanceUpkeepUnitOptions" :key="index" :label="item.label" :value="item.value" /> </el-select
            ></el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="负责人" prop="zrr"
              ><span v-if="viewForm">{{ detailRecord?.zrr || '-' }}</span
              ><el-input v-else v-model="detailRecord.zrr" placeholder="请输入" clearable
            /></el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="联系方式" prop="lxfs"
              ><span v-if="viewForm">{{ detailRecord?.lxfs || '-' }}</span
              ><el-input v-else v-model="detailRecord.lxfs" placeholder="请输入" clearable
            /></el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="flex justify-end gap-2">
          <el-button @click="detailVisible = false">
            <el-icon class="mr-1">
              <Close />
            </el-icon>
            关闭
          </el-button>
          <el-button type="primary" @click="onSave" v-if="formOperationType !== FormOperationTypeEnum.INFO">
            <el-icon class="mr-1">
              <Check />
            </el-icon>
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus';
import { Search, Edit, Plus, Close, Check } from '@element-plus/icons-vue';
import {
  EquipmentForm,
  equipmentGradeKeyName,
  equipmentGradeMap,
  equipmentPriorityKeyName,
  equipmentPriorityMap,
  equipmentStatusKeyName,
  equipmentStatusMap,
  equipmentTypeKeyName,
  equipmentTypeMap,
  EquipmentVO,
  getOptionsByKeyMap,
  maintenanceUpkeepUnitKeyName,
  maintenanceUpkeepUnitMap,
  safetyAttachmentKeyName,
  safetyAttachmentMap,
  safetyAttachmentTypeKeyName,
  safetyAttachmentTypeMap,
  specialEquipmentKeyName,
  specialEquipmentMap,
  specialEquipmentTypeKeyName,
  specialEquipmentTypeMap
} from '@/api/system/equipment/types';
import { DepartmentTree } from '@/api/system/department/types';
import { listDepartmentTree } from '@/api/system/department';
import { DeviceQuery, DeviceVO } from '@/api/system/device/types';
import { addEquipment, delEquipment, listEquipment, updateEquipment } from '@/api/system/equipment';
import { FormOperationTypeEnum } from '@/enums';
import { listAllDevice } from '@/api/system/device';

const formOperationType = ref(FormOperationTypeEnum.ADD);

const viewForm = computed(() => formOperationType.value === FormOperationTypeEnum.INFO);

const filters = reactive({
  sbmc: '',
  sbwh: '',
  sblx: undefined,
  sbdj: undefined,
  createDept: undefined
});

const queryLoading = ref(false);
const tableLoading = ref(false);

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

const tableData = ref<EquipmentVO[]>([]);

const indexMethod = (index: number) => (pagination.currentPage - 1) * pagination.pageSize + index + 1;

const fetchList = async () => {
  tableLoading.value = true;
  queryLoading.value = true;
  try {
    const params: DeviceQuery = {
      ...filters,
      pageSize: pagination.pageSize,
      pageNum: pagination.currentPage
    };
    listEquipment(params)
      .then((res) => {
        if (res.rows && res.rows?.length > 0) {
          tableData.value = res.rows;
          pagination.total = res?.total;
        } else {
          tableData.value = [];
        }
      })
      .catch((e) => {
        tableData.value = [];
        console.error(e);
      })
      .finally(() => {
        queryLoading.value = false;
        tableLoading.value = false;
      });
  } catch (error) {
    ElMessage.error('数据加载失败，请稍后重试');
  } finally {
    tableLoading.value = false;
    queryLoading.value = false;
  }
};

const handleQuery = () => {
  pagination.currentPage = 1;
  fetchList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchList();
};

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  fetchList();
};
interface EquipmentFormInfo extends EquipmentForm {
  createDeptName: string;
}
const baseForm: EquipmentFormInfo = {
  /** 所属装置ID（必填）*/
  sszz: undefined,
  /** 设备名称（必填）*/
  sbmc: undefined,
  /** 设备位号（必填）*/
  sbwh: undefined,
  /** 设备主次：0主设备，1附属设备，2其他（必填）*/
  sbzc: undefined,
  /** 设备类型：0动设备，1静设备，2电气，3仪表（必填）*/
  sblx: undefined,
  /** 是否特种设备：0否，1是（必填）*/
  tzsbNy: undefined,
  /** 特种设备分类：0压力容器，1压力管道，2锅炉（必填）*/
  tzsbfl: undefined,
  /** 是否为安全附件：0否，1是（必填）*/
  aqfjNy: undefined,
  /** 安全附件分类：0安全阀，1爆破片，2紧急切断，3压力表，4液位计，5测温仪表，6易熔塞，7其他（必填）*/
  aqfjfl: undefined,
  /** 设备等级：0一般，1关键，2核心（必填）*/
  sbdj: undefined,
  /** 设备状态：0运行，1停用，2备用，3维修，4待修，5过期（必填）*/
  sbzt: undefined,
  /** 规格型号（必填）*/
  sbxh: undefined,
  /** 生产日期（必填）*/
  scrq: undefined,
  /** 使用年限（必填）*/
  synx: undefined,
  /** 安装位置（必填）*/
  azwz: undefined,
  /** 安装日期（必填）*/
  azrq: undefined,
  /** 启用日期（必填）*/
  qyrq: undefined,
  /** 维护保养周期（必填）*/
  whbyzq: undefined,
  /** 维护保养单位：0天，1周，2旬，3月，4季，5半年，6年（必填）*/
  whbydw: undefined,
  /** 责任人（必填）*/
  zrr: undefined,
  /** 联系方式（必填）*/
  lxfs: undefined,
  /** 所属部门（必填）*/
  createDept: undefined,
  createDeptName: undefined
};

const formRef = ref<FormInstance>();
const detailVisible = ref(false);
const detailTitle = ref('详情');
const detailRecord = ref<EquipmentFormInfo | null>({ ...baseForm });

interface RuleForm {
  sszz: string;
  sbmc: string;
  sbwh: string;
  sbzc: string;
  sblx: string;
  tzsbNy: string;
  tzsbfl: string;
  aqfjNy: string;
  aqfjfl: string;
  sbdj: string;
  sbzt: string;
  sbxh: string;
  scrq: string;
  synx: string;
  azwz: string;
  azrq: string;
  qyrq: string;
  whbyzq: string;
  whbydw: string;
  zrr: string;
  lxfs: string;
  createDept: string;
}
const formRules = reactive<FormRules<RuleForm>>({
  sszz: [{ required: true, message: '请输入', trigger: 'blur' }],
  sbmc: [{ required: true, message: '请输入', trigger: 'blur' }],
  sbwh: [{ required: true, message: '请输入', trigger: 'blur' }],
  sbzc: [{ required: true, message: '请输入', trigger: 'blur' }],
  sblx: [{ required: true, message: '请输入', trigger: 'blur' }],
  tzsbNy: [{ required: true, message: '请输入', trigger: 'blur' }],
  tzsbfl: [{ required: true, message: '请输入', trigger: 'blur' }],
  aqfjNy: [{ required: true, message: '请输入', trigger: 'blur' }],
  aqfjfl: [{ required: true, message: '请输入', trigger: 'blur' }],
  sbdj: [{ required: true, message: '请输入', trigger: 'blur' }],
  sbzt: [{ required: true, message: '请输入', trigger: 'blur' }],
  sbxh: [{ required: true, message: '请输入', trigger: 'blur' }],
  scrq: [{ required: true, message: '请输入', trigger: 'blur' }],
  synx: [{ required: true, message: '请输入', trigger: 'blur' }],
  azwz: [{ required: true, message: '请输入', trigger: 'blur' }],
  azrq: [{ required: true, message: '请输入', trigger: 'blur' }],
  qyrq: [{ required: true, message: '请输入', trigger: 'blur' }],
  whbyzq: [{ required: true, message: '请输入', trigger: 'blur' }],
  whbydw: [{ required: true, message: '请输入', trigger: 'blur' }],
  zrr: [{ required: true, message: '请输入', trigger: 'blur' }],
  lxfs: [{ required: true, message: '请输入', trigger: 'blur' }],
  createDept: [{ required: true, message: '请输入', trigger: 'blur' }]
});

const onCreate = () => {
  formOperationType.value = FormOperationTypeEnum.ADD;
  restForm();
  detailVisible.value = true;
};

const onEdit = () => {
  formOperationType.value = FormOperationTypeEnum.EDIT;
};
const restForm = () => {
  detailRecord.value = { ...baseForm };
};

const onView = (row: EquipmentFormInfo) => {
  formOperationType.value = FormOperationTypeEnum.INFO;
  restForm();
  detailRecord.value = row;
  detailTitle.value = `${row.sbmc}（${row.sbwh}）`;
  detailVisible.value = true;
};

const onSave = () => {
  formRef.value.validate((valid, _fields) => {
    if (valid) {
      if (formOperationType.value === FormOperationTypeEnum.EDIT && detailRecord.value?.id) {
        updateEquipment(detailRecord.value)
          .then((_res) => {
            ElMessage.success('保存成功');
            detailVisible.value = false;
          })
          .catch((e) => {
            console.error(e);
          })
          .finally(() => {
            fetchList();
          });
      } else {
        addEquipment(detailRecord.value)
          .then((_res) => {
            ElMessage.success('保存成功');
            detailVisible.value = false;
          })
          .catch((e) => {
            console.error(e);
          })
          .finally(() => {
            fetchList();
          });
      }
    }
  });
};

const onDelete = async (row: EquipmentFormInfo) => {
  try {
    await ElMessageBox.confirm(`确认删除设备“${row.sbmc}（${row.sbwh}）”？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    tableLoading.value = true;
    await delEquipment(row.id);
    ElMessage.success('删除成功');
    await fetchList();
  } catch (error) {
    if (error !== 'cancel' && error !== 'close') {
      ElMessage.error('删除失败，请稍后重试');
    }
  } finally {
    tableLoading.value = false;
  }
};

const equipmentStatusTagType = (s: number) => equipmentStatusMap[s] ?? 'info';
const equipmentPriorityTagType = (s: string) => equipmentPriorityMap[s] ?? 'info';
const equipmentTypeTagType = (s: string) => equipmentTypeMap[s] ?? 'info';
const equipmentGradeTagType = (s: number) => equipmentGradeMap[s] ?? 'info';
const specialEquipmentTagType = (s: number) => specialEquipmentMap[s] ?? 'info';
const specialEquipmentTypeTagType = (s: number) => specialEquipmentTypeMap[s] ?? 'info';
const safetyAttachmentTagType = (s: number) => safetyAttachmentMap[s] ?? 'info';
const safetyAttachmentTypeTagType = (s: number) => safetyAttachmentTypeMap[s] ?? 'info';
const maintenanceUpkeepUnitTagType = (s: string) => maintenanceUpkeepUnitMap[s] ?? 'info';

const equipmentStatusOptions = getOptionsByKeyMap(equipmentStatusKeyName);
const equipmentGradeOptions = getOptionsByKeyMap(equipmentGradeKeyName);
const equipmentTypeOptions = getOptionsByKeyMap(equipmentTypeKeyName);
const equipmentPriorityOptions = getOptionsByKeyMap(equipmentPriorityKeyName);
const specialEquipmentOptions = getOptionsByKeyMap(specialEquipmentKeyName);
const specialEquipmentTypeOptions = getOptionsByKeyMap(specialEquipmentTypeKeyName);
const safetyAttachmentOptions = getOptionsByKeyMap(safetyAttachmentKeyName);
const safetyAttachmentTypeOptions = getOptionsByKeyMap(safetyAttachmentTypeKeyName);
const maintenanceUpkeepUnitOptions = getOptionsByKeyMap(maintenanceUpkeepUnitKeyName);
const departmentTreeOptions = ref<DepartmentTree[]>([]);

const belongDeviceOptions = ref<DeviceVO[]>([]);
const getBelongDeviceOptions = async () => {
  const res = await listAllDevice();
  if (res.data && res.data.length > 0) {
    belongDeviceOptions.value = res.data;
  } else {
    belongDeviceOptions.value = [];
  }
};
const getDepartmentTree = async () => {
  const res = await listDepartmentTree();
  if (res.data && res.data.length > 0) {
    departmentTreeOptions.value = res.data;
  } else {
    departmentTreeOptions.value = [];
  }
};

onMounted(async () => {
  await getDepartmentTree();
  await getBelongDeviceOptions();
  await fetchList();
});
</script>
